//
//  MainTabViewController.m
//  DaJiang
//
//  Created by sally on 16/9/29.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabViewController.h"
#import "ChatManager.h"

@interface MainTabViewController ()<IChatManagerDelegate>

@end

@implementation MainTabViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];

  [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:10], NSFontAttributeName, nil] forState:UIControlStateNormal];
  [[UITabBar appearance] setTintColor:GOrangeColor];

  // 状态栏颜色
  [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  [self setNeedsStatusBarAppearanceUpdate];
//  [[UIApplication sharedApplication] setStatusBarHidden:YES];

  //AppDelegate中实现tab切换的delegate
  AppDelegate *app = (AppDelegate *) [UIApplication sharedApplication].delegate;
  self.delegate = app;
}

- (void)dealloc {
  [self unregisterNotifications];
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - 进入页面加载的方法
- (void)setNotification {
  [self registerNotifications];
}

#pragma mark - IChatManagerDelegate 登录状态变化
#pragma mark 被其他设备踢掉的回调
- (void)didLoginFromOtherDevice {
  //退出环信
  [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
    //注销信鸽设备
    [OperationManager deleteXGDevice];
    
    //删除所有plist
    [[CommonMethod sharedCommonMethod]deleteAllPlist:^(BOOL isSuccess) {
      if (isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
          //退回到登录状态
          [self.navigationController popToRootViewControllerAnimated:YES];
          [[CommonMethod sharedCommonMethod] showAlertMessage:@"你的账号已在其他地方登录"];
        });
      }
    }];
    
  } onQueue:nil];
}

#pragma mark - EMChatManagerChatDelegate
#pragma mark 会话列表信息更新时的回调
- (void)didUpdateConversationList:(NSArray *)conversationList {
  [self setupUnreadMessageCount];
}

#pragma mark 未读消息数量变化回调
- (void)didUnreadMessagesCountChanged {
  [self setupUnreadMessageCount];
}

#pragma mark 离线非透传消息接收完成的回调
- (void)didFinishedReceiveOfflineMessages {
  [self setupUnreadMessageCount];
}

#pragma mark 收到在线消息时的回调
- (void)didReceiveMessage:(EMMessage *)message{
  if (message.ext) {
    [self addExtDateToDB:message];
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
      EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
      if (options.noDisturbStatus == ePushNotificationNoDisturbStatusClose) {
        //app不在前台且设置可推送时才发本地通知
        [ChatManager registerLocalNotification:message];
      }
    }
  }
  //删除不带扩展的会话
  else{
    [[EaseMob sharedInstance].chatManager removeConversationByChatter:message.conversationChatter deleteMessages:YES append2Chat:YES];
  }
}

#pragma mark 接收到离线非透传消息的回调
-(void)didReceiveOfflineMessages:(NSArray *)offlineMessages{
  for (EMMessage *message in offlineMessages) {
    if (message.ext) {
      [self addExtDateToDB:message];
    }
    //删除不带扩展的会话
    else{
      [[EaseMob sharedInstance].chatManager removeConversationByChatter:message.conversationChatter deleteMessages:YES append2Chat:YES];
    }
  }
}

#pragma mark - 私有方法
#pragma mark - 注册环信delegate
- (void)registerNotifications {
  [self unregisterNotifications];
  [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)unregisterNotifications {
  [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

#pragma mark 统计未读消息数
- (void)setupUnreadMessageCount {
  UINavigationController *nav3 = (UINavigationController *) self.viewControllers[2];
  [ChatManager setupUnreadMessageCount:nav3];
}

#pragma mark - 数据库操作
-(void)addExtDateToDB:(EMMessage *)message{
  Ext *ext = [[Ext alloc]init];
  ext.uid = [message.ext valueForKey:@"uid"];
  ext.avatar = [message.ext valueForKey:@"avatar"];
  ext.nickname = [message.ext valueForKey:@"nickname"];
  ext.username = message.conversationChatter;
  
  [ChatManager addExtDateToDB:ext];
}

@end
